<?php

namespace Cyv\Laravel;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

trait ApiException
{
    public function render($request, \Throwable $e)
    {
        $code        = 0;
        $msg         = '';
        $data        = [];
        $exceptsions = [
            HttpException::class                 => ['code' => 501, 'msg' => 'http请求错误，请稍后重试'],
            NotFoundHttpException::class         => ['code' => 502, 'msg' => '路由不存在'],
            MethodNotAllowedHttpException::class => ['code' => 503, 'msg' => '请求方法错误'],
            QueryException::class                => ['code' => 504, 'msg' => '数据不存在'],
            ModelNotFoundException::class        => ['code' => 505, 'msg' => '数据不存在'],
            \BadMethodCallException::class       => ['code' => 506, 'msg' => '方法不存在'],
            ThrottleRequestsException::class     => ['code' => 507, 'msg' => '请求次数太多'],

        ];
        foreach ($exceptsions as $class => $value) {
            if ($e instanceof $class) {
                $code = $value['code'];
                $msg  = $value['msg'];
            }
        }
        if ($e instanceof ValidationException) {
            $code = 599;
            $msg  = $e->getMessage();
        }
        if ($code) {
            if (!$msg) {
                $msg = $e->getMessage();
            }
        } else {
            $code = 500;
            $msg  = $e->getMessage();
            if (config('app.debug')) {
                $data = [
                    'message'   => $e->getMessage(),
                    'exception' => get_class($e),
                    'file'      => $e->getFile(),
                    'line'      => $e->getLine(),
                    'trace'     => $e->getTrace()
                ];
            }
        }

        return $this->error($code, $msg, $data);
    }

    public function error($code = 500, $msg = 'error', $data = [])
    {
        return response()->json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}
